<template>
  <div>
    <label v-if="label">{{ label }}</label>
    <slot></slot>
    <!-- 校验信息展示 -->
    <p v-if="error">{{ error }}</p>
  </div>
</template>

<script>
import Schema from "async-validator";
export default {
  inject: ["form"],
  data() {
    return {
      error: "" //error 是空说明校验通过
    };
  },
  props: {
    label: {
      type: String,
      default: ""
    },
    prop: {
      type: String,
      default: ""
    }
  },
  mounted() {
    this.$on("validate", () => {
      this.validate();
    });
  },
  methods: {
    //按照规则创建schema,让schema去校验这个数据源，校验的结果在回调函数中
    validate() {
      //规则
       const rules = this.form.rules[this.prop];
      //当前值
      const value = this.form.model[this.prop];
      //校验描述对象
      const desc= {[this.prop]:rules};
      //创建schema 实例
      const schema = new Schema(desc);
      return schema.validate({[this.prop]:value},errors=>{
        if(errors){
          this.error=errors[0].message;
        }else{
          //校验通过
            this.error="";
        }
      })
    }
  }
};
</script>

<style scoped></style>
